package com.spider.admin.service.client;

import com.spider.admin.conf.ResultMessage;
import com.spider.admin.conf.validator.Constants;
import com.spider.admin.exception.SpiderException;
import com.spider.admin.http.entity.PageResult;
import com.spider.admin.service.async.AsyncService;
import com.spider.admin.store.primary.mapper.AccountMapper;
import com.spider.admin.store.primary.mapper.ClientMapper;
import com.spider.admin.store.primary.model.ClientInfo;
import com.spider.admin.utils.CommonUtil;
import jakarta.annotation.Resource;
import jakarta.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class ClientServiceImpl implements ClientService {

    @Resource
    private ClientMapper clientMapper;

    @Resource
    private AccountMapper accountMapper;


    @Resource
    private AsyncService asyncService;

    @Override
    public int saveClient(ClientInfo clientInfo) throws SpiderException {
        clientInfo
                .setPid(CommonUtil.getShortUniqueId())
                .setClientKey(CommonUtil.getShortUniqueId())
                .setArchiveStatus(Constants.ACTIVE.getCode()).setGrantDate(CommonUtil.getCurrentDate("yyyy-MM-dd"));
        String tenantId = clientInfo.getTenantId();
        if (StringUtils.isEmpty(tenantId)) {
            throw new SpiderException(ResultMessage.FAILED_PARAMS_VALIDATE.getCode(), "租户ID不能为空");
        }
        long count = accountMapper.getActiveTenantCountById(tenantId);
        if (count <= 0) {
            throw new SpiderException(ResultMessage.FAILED_PARAMS_VALIDATE.getCode(), "租户未激活或不存在");
        }

        int i = clientMapper.saveClient(clientInfo);
        log.info("新增客户端：{}", clientInfo.getClientName());
        asyncService.asyncRefashPermsCache();
        return i;
    }

    @Override
    public PageResult<ClientInfo> queryClientByTenantId(String tenantId, Integer page, Integer pageSize, String clientName, String clientStatus) throws SpiderException {
        page = page == null || page.intValue() <= 0 ? 1 : page;
        pageSize = pageSize == null ? 10 : pageSize;
        long totalCount = clientMapper.getClientRecordNum(tenantId, clientName, clientStatus);
        int totalPage = (int) Math.ceil((double) totalCount / (double) pageSize);
        page = page > totalPage ? totalPage : page;
        page = page <= 0 ? 1 : page;
        PageResult<ClientInfo> result = new PageResult<>();
        result.setCurrentPage(page);
        result.setPageSize(pageSize);
        result.setTotal(totalCount);
        result.setTotalPage(totalPage);

        List<ClientInfo> records = clientMapper.queryClientByTenantId((page - 1) * pageSize, pageSize, tenantId, clientName, clientStatus);
        result.setList(records);

        return result;
    }

    @Override
    public ClientInfo queryClientById(String pid) throws SpiderException {

        return clientMapper.getClientById(pid);
    }

    @Override
    public int activeClient(String pid) throws SpiderException {
        ClientInfo client = new ClientInfo();
        client.setArchiveStatus(Constants.ACTIVE.getCode());
        int i = clientMapper.updateClient(client, pid);
        log.info("激活客户端：{}", pid);
        asyncService.asyncRefashPermsCache();
        return i;
    }

    @Override
    public int archiveClient(String pid) throws SpiderException {
        ClientInfo clientInfo = new ClientInfo();
        clientInfo.setArchiveStatus(Constants.ARCHIVE.getCode());
        int i = clientMapper.updateClient(clientInfo, pid);
        log.info("归档客户端：{}", pid);
        asyncService.asyncRefashPermsCache();
        return i;
    }

    @Override
    public int updateClient(ClientInfo clientInfo, String pid) throws SpiderException {
        long count=clientMapper.getClientCountUpdateName(pid,clientInfo.getClientName());
        if(count>0){
            throw new SpiderException(ResultMessage.FAILED_PARAMS_VALIDATE.getCode(), "客户端名称已经被占用");
        }
        int i = clientMapper.updateClient(clientInfo, pid);
        asyncService.asyncRefashPermsCache();
        return i;
    }

    @Override
    @Transactional
    public String changeClientKey(String pid) throws SpiderException {
        String newKey = CommonUtil.getShortUniqueId();
        ClientInfo client = new ClientInfo();
        client.setClientKey(newKey);
        int i = clientMapper.updateClient(client, pid);
        if (i > 0) {
            log.info("重置客户端Key：{}  成功", pid);
        } else {
            log.info("重置客户端Key：{}  失败", pid);
            throw new SpiderException(ResultMessage.FAILED.getCode(), "重置客户端Key失败");
        }
        asyncService.asyncRefashPermsCache();
        return newKey;
    }

    @Override
    public int removeClient(String clientId) throws SpiderException {
        int i = clientMapper.removeClient(clientId);
        if (i > 0) {
            asyncService.asyncRefashPermsCache();
        }
        return i;
    }
}

